$(function () {
    BASE.LOGIN.autoFillTel();
    BASE.LOGIN.loginVerify();
    BASE.LOGIN.initPage();
    BASE.LOGIN.isrememberLogin();
});
var  BASE = BASE||{}; //全局公用方法
BASE.LOGIN = (function () {
    var SELECTEDINSTERECT = []; // 选中的兴趣方向
    /************************************接口部分start*********************************/
    /*登录初始化*/
    function initPage() {
        var flag = location.href.split('?from=').pop();
        if(flag == 'index'){
            $('#login_container_wrap').height(600).show();
            weixinLogin();
        }
        $('#login_box').show();
    }
    /*获取兴趣方向*/
    function getInterest(obj) {
        $(obj).attr('disabled', true);
        var flag = $(obj).data('getDataFlag');
        if (flag) {
            $('#interestSelect').toggle();
            $(obj).attr('disabled', false);
            return;
        }
            BASE.apiGet('/device/mainCategory/list', function (data) {
            var result = _initInterestData(data);
            $('#insterestList').html(template('insterestList_tpl', {list: result}));
            $('#interestSelect').show();
            $(obj).attr('disabled', false);
            $(obj).data('getDataFlag', true);
        });
    }
    /*注册*/
    function register(obj) {
        var tel = $('#tel').val(),
            learnTypeIds = $('#learnType').data('id'),
            vcode = $('#code').val(),
            ycode = $('#ycode').val();
        if (!BASE.verifyTel(tel)) {
            return;
        }
        if (!vcode) {
            BASE.clearpop('请输入验证码', 2000);
            return;
        }
        $(obj).attr('disabled', true);
        var sendData = {
            mobile: tel,
            learnTypeIds: learnTypeIds,
            vcode: vcode,
            ycode: ycode,
        };
        BASE.postHttp('/device/member/register', sendData, function (res) {
            if (res.code != 200) {
                $(obj).attr('disabled', false);
                BASE.clearpop(res.message);
                return;
            }
           _loginSuessfn(res);
        })
    }
    /*重置密码*/
    function resetPassWord(obj) {
        var tel = $('#tel').val(),
            password = $('#password').val(),
            vcode = $('#code').val();
        if (!BASE.verifyTel(tel)) {
            return;
        }
        if (!vcode) {
            BASE.clearpop('请输入验证码', 2000);
            return;
        }
        if (!BASE.verifyPas(password)) {
            return;
        }
        $(obj).attr('disabled', true);
        var sendData = {
            mobile: tel,
            password: password,
            vcode: vcode,
        };
        BASE.postHttp('/device/member/resetPassword', sendData, function (res) {
            if (res.code != 200) {
                $(obj).attr('disabled', false);
                BASE.clearpop(res.message);
                return;
            }
            BASE.clearpop('重置密码成功去登录', 1000);
            setTimeout(function () {
                window.location.href = '/login.html?tel=' + tel;
            }, 2000);
        })
    }
    /*退出登录*/
    function exitLogin() {
        BASE.apiPost('/device/member/logout', function () {
            BASE.clearAll();
            location.href = '/login.html';
        })
    }
    /*登录*/
    function login(obj) {
        var tel = $('#tel').val(),
            password = $('#password').val();
        if (!BASE.verifyTel(tel)) {
            return;
        }
        if (!BASE.verifyPas(password)) {
            return;
        }
        $(obj).attr('disabled', true);
        var sendData = {
            mobileOrNickName: tel,
            password: password,
        };
        BASE.postCommon('/device/member/loginWithPwd', sendData, function (res) {
            $(obj).attr('disabled', false);
            if (res.code != 200) {
                BASE.clearpop(res.message);
                return;
            }
            _loginSuessfn(res);
            BASE.COMMON.userInfoFill(); /*头部用户信息*/
        })
    }

    /*是否记住了登录*/
    function isrememberLogin() {
        if(BASE.getStore('saveLoginIs')){
           $('#remember').trigger('click');
        }
    }
    /*通过验证码登录*/
    function loginBycode(obj) {
        var tel = $('#tel').val(),
            vcode = $('#code').val();
        if (!BASE.verifyTel(tel)) {
            return;
        }
        if (!vcode) {
            return;
        }
        $(obj).attr('disabled', true);
        var sendData = {
            mobile: tel,
            vcode: vcode,
        };
        BASE.postHttp('/device/member/loginWithVcode', sendData, function (res) {
            $(obj).attr('disabled', false);
            if (res.code != 200) {
                BASE.clearpop(res.message);
                return;
            }
            _loginSuessfn(res);
        })
    }
    /*获取图形验证码*/
    function getImgeCode(obj) {
        var tel = $('#tel').val();
        if (!BASE.verifyTel(tel)) {
            return;
        }
        var sendData = {
            mobile: tel,
        };
        BASE.postHttp('/device/member/getCaptcha', sendData, function (res) {
            $(obj).attr('disabled', false);
            if (res.code != 200) {
                BASE.clearpop(res.message);
                return;
            }
            $('#imgCode').attr('src', 'data:image/png;base64,' + res.data.imgData);
            $('#codeImg').val('');  // 每次获取后清空验证码重新输入
            $('#writeImgCode').show();
            $('body').data('obj', obj); // 存储要倒计时的按钮
        });
    }
    /*获取手机验证码 vcodeStyle 1注册,2登录,3账户注销,4提现,5手机绑定,6绑定账户)*/
    function getCode(type,callback) {
        var tel = $('#tel').val();
        var $this = $(this);
      /*  var captchaCode = $('#codeImg').val();*/
        if (!BASE.verifyTel(tel)) {
            return;
        }
       /* if (!captchaCode) {
            BASE.clearpop('请输入图片验证码');
            return;
        }*/
        var sendData = {
            mobile: tel,
          /*  captchaCode: captchaCode,*/
            vcodeStyle: type,
        };
        BASE.postHttp('/device/member/sendMobileCode', sendData, function (res) {
            if (res.code != 200) {
                BASE.clearpop(res.message);
                $this.attr('disabled', false);
                return;
            }
            BASE.clearpop('短信已成功发送到' + tel, 2000);
            BASE.mortime($this);
            if(callback && typeof callback =='function'){
                callback();
            }
        });
    }
    /************************************接口部分end**********************************/

    /************************************事件部分start**********************************/
    /*兴趣方向的选择*/
    $('#insterestList').on('click', '.insterest', function () {
        if (SELECTEDINSTERECT.length >= 5 && !$(this).hasClass('checked')) {
            BASE.clearpop('最多可选择5个兴趣方向');
            return;
        }
        $(this).toggleClass('checked');
        var result = [];
        $('#insterestList .checked').each(function () {
            var temp = {
                name: $(this).text().trim(),
                id: $(this).data('id'),
            };
            result.push(temp);
        });
        SELECTEDINSTERECT = result;
        /*选择结果的展示*/
        _renderSelected();
    });
    /*选中兴趣方向数据渲染*/
    function _renderSelected() {
        if (SELECTEDINSTERECT.length > 0) {
            $('#insterestSelected').html(template('insterestSelected_tpl', {list: SELECTEDINSTERECT}));
        } else {
            $('#insterestSelected').html('');
        }
    }
    /*获取的兴趣方向的数据处理*/
    function _initInterestData(arr) {
        var result = [];
        arr.forEach(function (item) {
            if (item.parentId === '0') {
                result.push(item);
            }
        });
        result.forEach(function (parent) {
            arr.forEach(function (item) {
                if (item.parentId === parent.id) {
                    if (!parent.child) {
                        parent.child = [item];
                    } else {
                        parent.child.push(item);
                    }
                    return false;
                }
            })
        });
        return result;
    }
    /*兴趣方向的保存或关闭*/
    function savaInterest(flag) {
        if (!flag) { // 关闭
            $('#learnType').val('');
            $('#learnType').data('id', '');
            $('#interestSelect').hide();
            return;
        }
        var result = [];
        var resultID = [];
        SELECTEDINSTERECT.forEach(function (item) {
            result.push(item.name);
            resultID.push(item.id);
        });
        $('#learnType').val(result.join(','));
        $('#learnType').data('id', resultID.join(','));
        $('#interestSelect').hide();
    }
    /*手机号码自动填充*/
    function autoFillTel() {
        var href = window.location.href;
        if (href.indexOf('tel=') > -1) {
            $('#tel').val(href.split('tel=').pop());
        }
    }
    /*登录成功执行*/
    function _loginSuessfn(res) {
        var token = res.data.token;
        BASE.clearpop('登录成功，页面即将跳转', 1000);
        BASE.clearAll();
        BASE.setStore('userToken', token);
        BASE.setStore('userInfo', res.data.member);
        BASE.setCookie('SESSION', Base64.encode(token), 7);
        _loginSuccessJump();
    }
    /*登录后跳转*/
    function _loginSuccessJump() {
        var refer = document.referrer;
        var pathname =window.location.pathname.toLowerCase();
        /*主页登录跳转*/
        if ( !pathname || pathname== '/' || pathname == 'index.html') {
            refer = '/index.html';
        }
        /*根据来源跳转*/
        if (refer.toLowerCase().indexOf('forgotpassword') > -1
            || refer.toLowerCase().indexOf('login') > -1
            || refer.toLowerCase().indexOf('qq.com') > -1 /* 来源qq或微信*/
            || refer.toLowerCase().indexOf('weixin.') > -1
            ||!refer
            || refer.toLowerCase().indexOf('register') > -1) {
            refer = '/index.html';
        }
        window.location.href = refer;
    }
    /*显示输入图片验证码*/
    function showWriteImgCode(obj, type) {
        var tel = $('#tel').val();
        if (!BASE.verifyTel(tel)) {
            return;
        }
        $('body').data('type', type);
        $(obj).attr('disabled', true);
        getImgeCode(obj);
    }
    /*点击微信登录*/
    function weixinLogin(obj) {
        var state = (new Date()).getTime();
        var flag = $(obj).data('flag');
        if(flag){
            $('#login_container_wrap').show();
            return;
        }
        var weixin = new WxLogin({
            self_redirect:false,
            id:"login_container",
            appid: "wxf8ac08f32b02c7eb",
            scope: "snsapi_login",
            redirect_uri: BASE.baseUrl+"/loginweixin.html",
            state: state,
            style: "",
            href: ""
        });
        $('#login_container_wrap').show();
    }
    /*QQ登录*/
    function loginByQQ() {
        var oOpts = {
            appId:BASE.isLocal()? "101501138":"101496819",
            redirectURI:BASE.baseUrl+"/loginQQ.html"
        };
        QC.Login.showPopup(oOpts);
    }
    /*登录部分公用验证*/
    function loginVerify() {
        /*手机号验证*/
        $('#tel').focusout(function () {
            var tel = $('#tel').val();
            if (!BASE.verifyTel(tel)) {
                $('#tel').next('.wrong-tips').fadeIn();
            } else {
                $('#tel').next('.wrong-tips').fadeOut();
            }
        });

        /*密码验证*/
        $('#password').focusout(function () {
            var password = $('#password').val();
            if (!BASE.verifyPas(password)) {
                $('#password').next('.wrong-tips').fadeIn();
            } else {
                $('#password').next('.wrong-tips').fadeOut();
            }
        });
    }
    $('#remember').on('click',function () {
        var flag = $(this).is(':checked');
        if(!flag){
            BASE.removeStore('saveLoginIs');
            BASE.setCookie('saveLoginIs','',-1);
            return;
        }
        BASE.setStore('saveLoginIs',new Date());
        BASE.setCookie('saveLoginIs',new Date(),7);
    })
    /************************************事件部分end*********************************/

    return{
        initPage:initPage,
        getInterest:getInterest,
        register:register,
        exitLogin:exitLogin,
        login:login,
        resetPassWord:resetPassWord,
        loginBycode:loginBycode,
        getImgeCode:getImgeCode,
        getCode:getCode,
        showWriteImgCode:showWriteImgCode,
        autoFillTel:autoFillTel,
        savaInterest:savaInterest,
        loginVerify:loginVerify,
        weixinLogin:weixinLogin,
        loginByQQ:loginByQQ,
        loginSuccess:_loginSuessfn,
        isrememberLogin:isrememberLogin,
    }
})();